package com.prp.gwt.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Transaction;

import com.prp.db.DAOFactory;
import com.prp.db.HibernateSessionFactory;
import com.prp.db.idao.IAuthenticationDAO;
import com.prp.db.idao.IUserInformationDAO;
import com.prp.db.po.Authentication;

public class RegisterActivate extends HttpServlet{

	private static final long serialVersionUID = -9174600377503129917L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String para = req.getParameter("autoCode");
		DAOFactory factory = DAOFactory.getDAOFactory();
		IAuthenticationDAO authDAO = factory.getAuthenticationDAO();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			List<Authentication> l = authDAO.findByAuthCode(para);
			if(l == null)
				resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			Authentication auth = (Authentication)l.get(0);
			if(null != auth){
				userDAO.findById(auth.getUserId()).setActivated(true);
				req.getSession().setAttribute("usr", auth.getUserId());
			}
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		} finally {
			HibernateSessionFactory.getSession().close();
			req.getRequestDispatcher("/activate.html").forward(req, resp);
		}
	}

}
